package com.ll.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.ll.common.constant.ProductConstant;
import com.ll.common.to.SkuHasStockTo;
import com.ll.common.to.SkuMemberTo;
import com.ll.common.to.SpuBoundTo;
import com.ll.common.to.es.SkuEsModel;
import com.ll.common.utils.R;
import com.ll.gulimall.product.entity.*;
import com.ll.gulimall.product.feign.CouponFeignService;
import com.ll.gulimall.product.feign.SearchFeignService;
import com.ll.gulimall.product.feign.WareFeignService;
import com.ll.gulimall.product.service.*;
import com.ll.gulimall.product.vo.*;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ll.common.utils.PageUtils;
import com.ll.common.utils.Query;

import com.ll.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService imagesService;

    @Autowired
    AttrService attrService;

    @Autowired
    ProductAttrValueService attrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Resource
    CouponFeignService couponFeignService;

    @Autowired
    WareFeignService wareFeignService;


    @Transactional
    @Override
    //TODO 完善接口 高级篇
    public void save(SpuSaveVo vo) {
        //1、保存spu基本信息 pms_spu_info'
        SpuInfoEntity supInfo = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, supInfo);
        supInfo.setCreateTime(new Date());
        supInfo.setUpdateTime(new Date());
        this.saveBaseSupInfo(supInfo);

        //2、保存spu的描述图片 pms_spu_info_desc
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity supDesc = new SpuInfoDescEntity();
        supDesc.setSpuId(supInfo.getId());
        supDesc.setDecript(String.join(",", decript));
        spuInfoDescService.saveSupInfoDesc(supDesc);

        //3、保存spu的图片集 pms_spu_images
        List<String> images = vo.getImages();
        imagesService.saveImages(supInfo.getId(), images);

        //4、保存spu的规格参数; pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity byId = attrService.getById(attr.getAttrId());
            attrValueEntity.setAttrName(byId.getAttrName());
            attrValueEntity.setAttrValue(attr.getAttrValues());
            attrValueEntity.setQuickShow(attr.getShowDesc());
            attrValueEntity.setSpuId(supInfo.getId());
            return attrValueEntity;
        }).collect(Collectors.toList());
        attrValueService.saveProductAttr(collect);

        //5、保存spu的积分信息;gulimall_sms->smr_spu_bounds
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        spuBoundTo.setSupId(supInfo.getId());
        BeanUtils.copyProperties(vo.getBounds(), spuBoundTo);
        if (spuBoundTo.getGrowBounds().compareTo(BigDecimal.valueOf(0)) == 1 && spuBoundTo.getBuyBounds().compareTo(BigDecimal.valueOf(0)) == 1) {
            R save = couponFeignService.save(spuBoundTo);
            if (save.getCode() != 0) {
                log.error("spu积分信息添加失败");

            }
        }


        //6、保存当前spu对应的所有sku信息;
        //6.1) 、 sku的基本信.息.;pms_sku_info
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(sku -> {
                String defaultImage = "";
                for (Images image : sku.getImages()) {

                    if (image.getDefaultImg() == 1) {
                        defaultImage = image.getImgUrl();
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(supInfo.getBrandId());
                skuInfoEntity.setCatalogId(supInfo.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(defaultImage);
                skuInfoEntity.setSpuId(supInfo.getId());
                skuInfoService.saveSkuInfo(skuInfoEntity);
                List<SkuImagesEntity> imagesEntityList = sku.getImages().stream().map(img -> {
                    //6.2) 、 sku的图片信息.; pms_sku_images
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    BeanUtils.copyProperties(img, skuImagesEntity);
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuImagesEntity;

                }).filter(item -> {
                    return item.getImgUrl() != null && !"".equals(item.getImgUrl());
                }).collect(Collectors.toList());

                skuImagesService.saveBatch(imagesEntityList);


                //6.3) 、 sku的销售属性信息:pms_sku_sale_attr_value
                List<Attr> attr = sku.getAttr();
                List<SkuSaleAttrValueEntity> valueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity valueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, valueEntity);
                    valueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return valueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(valueEntities);

                //6.4)、sku的优惠、满减等信息;guLimalLl_sms->sms_sku_ladder\sms_sku_full_reduction\sms_member_price

                SkuMemberTo skuMemberTo = new SkuMemberTo();
                List<MemberPrice> memberPrice = sku.getMemberPrice();
                System.out.println(memberPrice);
                BeanUtils.copyProperties(sku, skuMemberTo);
                skuMemberTo.setSkuId(skuInfoEntity.getSkuId());
                //远程调用的前提是发送有意义的请求
                if (skuMemberTo.getFullCount() > 0 ||
                        skuMemberTo.getReducePrice().
                                compareTo(BigDecimal.valueOf(0)) == 1) {
                    R r1 = couponFeignService.saveSkuMember(skuMemberTo);
                    if (r1.getCode() != 0) {
                        log.error("sku优惠信息添加失败");

                    }
                }

            });
        }


    }

    @Override
    public void saveBaseSupInfo(SpuInfoEntity supInfo) {
        this.baseMapper.insert(supInfo);
    }

    /**
     * 根据条件查询spu信息
     *
     * @param params
     * @return
     */
    @Override
    public PageUtils findBycondition(Map<String, Object> params) {
        QueryWrapper<SpuInfoEntity> wrapper = new QueryWrapper<>();

        //   key: '华为',//检索关键字
        //   catelogId: 6,//三级分类id
        //   brandId: 1,//品牌id
        //   status: 0,//商品状态
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> {
                w.eq("id", key).or().like("spu_name", key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (!"0".equals(catelogId)) {
            wrapper.eq("catalog_id", catelogId);

        }
        String brandId = (String) params.get("brandId");
        if (!"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);

        }
        String status = (String) params.get("status");
        if (!"".equals(status) && status != null) {
            wrapper.eq("publish_status", status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    SearchFeignService searchFeignService;

    /**
     * 上架商品
     *
     * @param spuId
     */
    @Transactional
    @Override
    public void up(Long spuId) {

        //1、查出当前spuid对应的所有sku信息，品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        // 拿到SkuIds的集合
        List<Long> skuIds = skus.stream().map(sku -> sku.getSkuId()).collect(Collectors.toList());

        // 拿到SkuIds拆查询该商品是否有库存
        Map<Long, Boolean> map = null;
        try {
            R r = wareFeignService.hasStock(skuIds);


            List<SkuHasStockTo> data =
                    r.getData(new TypeReference<List<SkuHasStockTo>>() {
                    });
            map = data.stream().collect(Collectors.toMap(SkuHasStockTo::getSkuId, SkuHasStockTo::getHasStock));
        } catch (Exception e) {
            log.error("仓库服务查询异常：原因{}", e);
        }
        Map<Long, Boolean> finalMap = map;

        //查询当前sku可以被检索的规格属性
        //拿到该spu的所有Attr属性Id
        List<ProductAttrValueEntity> attrValueEntityList = attrValueService.listforspu(spuId);
        List<Long> attrIds = attrValueEntityList.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        System.out.println("该spu的所有属性Id" + attrIds);

        //根据AttrIds查询可以被检索的属性 返回该属性的AttrId集合
        List<Long> attrSearch = attrService.selectSearchAttr(attrIds);
        //转换为Set 方便操作  可以被检索的属性
        Set<Long> attrIdsSet = new HashSet<>(attrSearch);
        //遍历属于该spu的属性 过滤掉id不等于可以被检索属性的Id
        List<SkuEsModel.Attrs> esAttrs = attrValueEntityList.stream().filter(item -> {
            //如果包括返回true 可以被检索的属性
            return attrIdsSet.contains(item.getAttrId());
        }).map(item -> {
            //过滤返回可以被检索的属性 返回
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());
        System.out.println(esAttrs + "封装过后的数据");


        //2、封装每个Sku的信息

        List<SkuEsModel> upSkus = skus.stream().map(sku -> {
            //封装数据
            SkuEsModel skuEsModel = new SkuEsModel();
            skuEsModel.setSkuPrice(sku.getPrice());
            skuEsModel.setSkuImg(sku.getSkuDefaultImg());
            //商品热度
            skuEsModel.setHotScore(0L);
            skuEsModel.setHasStock(finalMap.get(sku.getSkuId()) == null ? true : finalMap.get(sku.getSkuId()));//是否有库存
            // 设置品牌、分类
            BrandEntity brand = brandService.getById(sku.getBrandId());
            skuEsModel.setBrandImg(brand.getLogo());
            skuEsModel.setBrandName(brand.getName());
            CategoryEntity cata = categoryService.getById(sku.getCatalogId());
            skuEsModel.setCatalogName(cata.getName());
            System.out.println(skuEsModel
                    .getCatalogName());
            //设置Es检索的属性
            skuEsModel.setAttrs(esAttrs);
            BeanUtils.copyProperties(sku, skuEsModel);
            return skuEsModel;
        }).collect(Collectors.toList());


        R r = searchFeignService.productUp(upSkus);
        if (r.getCode() == 0) {
            // 改变当前Spu状态
            baseMapper.updateSpuStatus(spuId, ProductConstant.ProductEnum.UP_PRODUCT.getCode());
        } else {
            // TODO 远程接口失败 重复调用？ 接口幂等性？
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {

        SkuInfoEntity skuInfo = skuInfoService.getById(skuId);

        SpuInfoEntity spuInfo = this.getById(skuInfo.getSpuId());
        return spuInfo;
    }

}